home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1106 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.2 KB

  1. Path: atglab.bls.com!Alun.Champion
  2. From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Help with gettng 2 chars into an integer!
  5. Date: 11 Jan 1996 15:01:36 GMT
  6. Organization: Computer People Inc.
  7. Message-ID: <ALUN.CHAMPION.96Jan11100137@g7240065.bridge.bst.bls.com>
  8. References: <4d2eh1$7pm@usc.edu>
  9. NNTP-Posting-Host: bstfirewall.bst.bls.com
  10. In-reply-to: wawda@scf.usc.edu's message of 11 Jan 1996 07:33:53 GMT
  11.  
  12. In article <4d2eh1$7pm@usc.edu> wawda@scf.usc.edu (Abu Wawda) writes:
  13.  
  14. : Hi. I can't seem to figure out how to do this. Basically I have to chars that 
  15. : I want to put into a 2-byte integer. It seems easy at first, but I can't seem 
  16. : to figure out to do it with the bit-fidling operators (shifting or masking). 
  17. : Simple put, I'd like to do:
  18.  
  19. :       char a,b;
  20. :       int c;
  21.  
  22. :       a = 'A';
  23. :       b = 'B';
  24. :       c = ? /* the first byte in c should contain the value of a, and the 
  25. : second byte should contain the value of b */
  26.  
  27. A couple of solutions
  28.  
  29. With bit shifting (assumes 8 bit bytes):
  30.  
  31.   c = (a << 8) | b;
  32.  
  33. With a union (assumes ???? endianess):
  34.  
  35.   union {
  36.       char a[2];
  37.       short c;
  38.   } fred;
  39.  
  40.   fred.a[1] = 'A';
  41.   fred.a[2] = 'B';
  42.  
  43. And thats it.
  44.  
  45. Hope this helps
  46. Regards
  47.  
  48.     -A.
  49. -- 
  50. | A.Champion                |
  51.